
'use strict'

import axios from 'axios'
import { camelizeKeys } from 'humps'

/**
 * @name 请求接口简单封装
 * @type Object
 * @param {
 *   headers = {},
 *   method = 'GET',
 *   params = {},
 *   data = {},
 *   isHeaders = true,
 *   responseType = 'json',
 *   contentType = '',
 *   isResolve = true
 * }
 * @example this.$fetch({
 *    method: 'PUT | POST | DELETE | PATCH',
 *    data: {...})
 *    .then(res => {})
 *    .catch(err => {});
 * @description 'here is a simple package for js.';
 * @returns Promise
 */

// 基础路由
if (window.location.host === 'dev.yitun.net' || window.location.host === 'cjdev.net') {
  axios.defaults.baseURL = 'http://api.cjdev.net/v1'
} else {
  axios.defaults.baseURL = 'https://api.changjianapp.com/v1'
}
// 允许使用token
axios.defaults.withCredentials = true
// 请求响应时间默认
axios.defaults.timeout = 15000
// 响应最大的内容尺寸
axios.defaults.maxContentLength = 60000
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (err) {
  // 对响应错误做点什么
  return Promise.reject(checkStatus(err))
})

const requestData = obj => {
  let {
    url = '',
    headers = {}, method = 'GET', params = {}, data = {},
    responseType = 'json', contentType = '',
    isResolve = true, isToken = false, event = {}
  } = obj
  let authorKey =  ''

  if (isToken) { headers['Authorization'] = authorKey }
  if (isResolve) { data = data && JSON.stringify(data) }
  contentType = contentType || 'application/json;charset=UTF-8'
  method = (method && method.toLocaleUpperCase()) || 'GET'
  return new Promise((resolve, reject) => {
    axios({
      url,
      headers,
      method,
      params,
      data,
      responseType,
      contentType
    }).then(res => {
      let status = res.status

      if (status !== 200) { return reject(res) }
      let data = camelizeKeys(res.data)
      return resolve(data)
    }).catch(err => {
      reject(checkStatus(err))
      // reject({code:765,message:'网络异常请稍后在试'})
    })
  })
}

export const fetch = obj => requestData(obj)

export default {
  install (Vue) {
    Vue.prototype.$fetch = fetch
  }
}

/**
 *  @name 状态码校验
 *  @param response
 *  @return {*}
 */
function checkStatus (response) {
  // 有响应时校验状态
  if (response) {
    // -10 自己定义，连接错误的status
    const status = response.status || -10
    if (status === 200 || status === 304 || status === 400) {
      return response.data
    } else {
      let errorInfo = ''
      switch (status) {
        case -1:
          errorInfo = '远程服务响应失败,请稍后重试'
          break
        case 400:
          errorInfo = '400: 错误请求'
          break
        case 401:
          errorInfo = '401: 访问令牌无效或已过期'
          break
        case 403:
          errorInfo = '403: 拒绝访问'
          break
        case 404:
          errorInfo = '404：资源不存在'
          break
        case 405:
          errorInfo = '405: 请求方法未允许'
          break
        case 408:
          errorInfo = '408: 请求超时'
          break
        case 500:
          errorInfo = '500：访问服务失败'
          break
        case 501:
          errorInfo = '501：未实现'
          break
        case 502:
          errorInfo = '502：无效网关'
          break
        case 503:
          errorInfo = '503: 服务不可用'
          break
        // 其他错误
        default:
          errorInfo = `网络异常，连接错误${status}`
      }
      return {status, message: errorInfo}
    }
  }
  // 异常状态下，返回错误信息
  return {status: -404, message: '网络异常'}
}
